#include "SoundLevelMeter.h"

//构造函数
SoundLevelMeter::SoundLevelMeter(){

}
//析构函数
SoundLevelMeter::~SoundLevelMeter(){
    cloes();
}

//打开操作
bool SoundLevelMeter::open(const char *device, int baud){
    //创建modbus连接句柄
    mb = modbus_new_rtu(device, baud, 'N', 8, 1);
    if (mb == NULL) {
        std::cerr << "Unable to create the modbus context\n";
        return false;
    }

    // 设置从设备ID
    modbus_set_slave(mb, slave_address);

    // 连接到Modbus RTU从设备
    mb_conn = modbus_connect(mb);
    if (mb_conn == -1) {
        std::cerr << "Connection failed: " << modbus_strerror(errno) << "\n";
        modbus_free(mb);
        return -1;
    }

    return true;
}

//关闭操作
bool SoundLevelMeter::cloes(void){
    modbus_close(mb);
    modbus_free(mb);
    return true;
}

//读取声级计数据并返回声级数据
float SoundLevelMeter::get_db(void){
    uint16_t tab_reg[1];
    int addr = 0; // 起始地址
    int nb = 1;   // 寄存器数量
    // 读取寄存器
    int rc = modbus_read_registers(mb, addr, nb, tab_reg);
    if (rc == -1) {
        std::cerr << "Failed to read registers: " << modbus_strerror(errno) << std::endl;
        modbus_free(mb);
        return -1;
    }

    return ((float)tab_reg[0])/10;
}




